package org.jeecg.feishu.api.provider;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.jeecg.common.api.dto.message.BusMessageDTO;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.feishu.api.dto.Message;
import org.jeecg.feishu.api.dto.MessageCondition;
import org.jeecg.feishu.api.dto.message.TextContent;
import org.jeecg.feishu.api.service.FeishuMessageService;
import org.jeecg.modules.system.provider.IThirdMessageProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FeishuMessageProvider implements IThirdMessageProvider {

	@Autowired
	private ISysBaseAPI iSysBaseAPI;

	@Autowired
	private FeishuMessageService feishuMessageService;

	@Override
	public void send(BusMessageDTO message) {
		try {
			MessageCondition condition = new MessageCondition();

			String userStr = message.getToUser();
			List<String> toUsers = new ArrayList<String>();
			if (userStr.contains(",")) {
				List<String> userList = Arrays.asList(userStr.split(","));
				for (String id : userList) {
					LoginUser _user = iSysBaseAPI.getUserByName(id);
					toUsers.add(_user.getThirdId());
				}

			} else {
				LoginUser _user = iSysBaseAPI.getUserByName(userStr);
				toUsers.add(_user.getThirdId());
			}
			TextContent context = new TextContent();
			context.setText(message.getTitle());
			condition.setUserIds(toUsers);
			condition.setMsgType("text");
			condition.setContent(context);
			Message result = feishuMessageService.send(condition);
			System.out.println(result.toString());
		} catch (Exception e) {
		}
	}

	@Override
	public void sendSimpleMsg(MessageDTO message) {
		try {
			MessageCondition condition = new MessageCondition();

			String userStr = message.getToUser();
			List<String> toUsers = new ArrayList<String>();
			if (userStr.contains(",")) {
				List<String> userList = Arrays.asList(userStr.split(","));
				for (String id : userList) {
					LoginUser _user = iSysBaseAPI.getUserByName(id);
					toUsers.add(_user.getThirdId());
				}

			} else {
				LoginUser _user = iSysBaseAPI.getUserByName(userStr);
				toUsers.add(_user.getThirdId());
			}
			TextContent context = new TextContent();
			context.setText(message.getTitle());
			condition.setUserIds(toUsers);
			condition.setMsgType("text");
			condition.setContent(context);
			Message result = feishuMessageService.send(condition);
			System.out.println(result.toString());
		} catch (Exception e) {
		}
	}

}
